<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form';
import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';

import { h, onMounted, ref } from 'vue';

import { useAccess } from '@vben/access';
import { Page } from '@vben/common-ui';

import { message, Tag } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  kickoutByLoginId,
  logoutByLoginId,
  onlineUserList,
} from '#/api/sys/user';
import { TableAction } from '#/components/table-action';
import { getRelativeTime } from '#/util/tool';

import OnlineUserDetail from './online-user-detail.vue';

const { hasAccessByCodes } = useAccess();

const dataSource = ref([]);
const onlineUserDetailRef = ref();
const handlePage = (params: any) => {
  const { pageNum, pageSize, keywords } = params;

  // 1. 从dataSource获取所有数据
  let filteredData = [...dataSource.value];

  // 2. 如果有关键词，进行过滤（匹配id、userName或realName）
  if (keywords) {
    const keywordStr = keywords.toString().toLowerCase();
    filteredData = filteredData.filter(
      (item: any) =>
        item.id?.toString().toLowerCase().includes(keywordStr) ||
        item.userName?.toLowerCase().includes(keywordStr) ||
        item.realName?.toLowerCase().includes(keywordStr),
    );
  }

  // 3. 返回分页结果
  return Promise.resolve({
    recordCount: filteredData.length,
    totalPage: Math.ceil(filteredData.length / pageSize),
    rows: filteredData.slice((pageNum - 1) * pageSize, pageNum * pageSize),
  });
};
const formOptions: VbenFormProps = {
  collapsed: true,
  wrapperClass: 'grid-cols-12', // 12栅格,
  commonConfig: {
    labelWidth: 60,
    formItemClass: 'col-span-4',
  },
  resetButtonOptions: {
    show: true,
  },
  actionLayout: 'inline',
  actionPosition: 'left',
  showCollapseButton: false,
  schema: [
    {
      component: 'Input',
      fieldName: 'keywords',
      label: '关键字',
      componentProps: {
        placeholder: '请输入账户ID、用户名、姓名',
        allowClear: true,
      },
    },
  ],
};
const gridOptions: VxeGridProps<any> = {
  columns: [
    { field: 'id', title: '账户ID' },
    {
      field: 'userName',
      title: '账户信息（用户名/姓名）',
      slots: {
        default: ({ row }) => {
          return `${row.userName}（${row.realName}）`;
        },
      },
    },
    {
      field: 'loginTime',
      title: '会话创建于',
      slots: {
        default: ({ row }) => {
          return h('div', { class: 'text-center' }, [
            h('span', `${row.loginTime} - `),
            h(
              'span',
              {
                style: {
                  color: 'green',
                },
              },
              getRelativeTime(row.loginTime),
            ),
          ]);
        },
      },
    },
    {
      field: 'expireTime',
      title: '会话失效于',
      slots: {
        default: ({ row }) => {
          return h('div', { class: 'text-center' }, [
            h('span', `${row.expireTime} - `),
            h(
              'span',
              {
                style: {
                  color: 'green',
                },
              },
              getRelativeTime(row.expireTime),
            ),
          ]);
        },
      },
    },
    {
      field: 'tokenList',
      title: '登录设备',
      slots: {
        default: ({ row }) =>
          h(
            Tag,
            {
              color: 'blue',
              class: 'cursor-pointer',
              onClick: handleDetail.bind(null, row),
            },
            () => `${row.tokenList ? row.tokenList.length : 0}个客户端`,
          ),
      },
    },
    {
      width: 160,
      title: '操作',
      align: 'center',
      slots: { default: 'ACTION' },
      fixed: 'right',
    },
  ],
  toolbarConfig: {
    refresh: false, // 刷新
    print: false, // 打印
    export: false, // 导出
    // custom: true, // 自定义列
    zoom: true, // 最大化最小化
    // slots: {
    //   buttons: 'toolbar-buttons',
    // },
    custom: {
      // 自定义列-图标
      icon: 'vxe-icon-menu',
    },
    tools: [
      {
        code: 'my-refresh',
        icon: 'vxe-icon-repeat',
        circle: true,
        title: '刷新',
      },
    ],
  },
  border: false,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        return await handlePage({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
      },
    },
  },
};
const gridEvents: VxeGridListeners<any> = {
  toolbarToolClick: (event) => {
    if (event.code === 'my-refresh') {
      requestData();
    }
  },
};
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents,
});
const requestData = () => {
  onlineUserList({}).then((res) => {
    dataSource.value = res;
    gridApi.reload();
  });
};
const handleDetail = (record: any) => {
  if (hasAccessByCodes(['admin', 'btn:onlineUser:detail'])) {
    onlineUserDetailRef.value.setData({
      record,
      gridApi,
    });
    onlineUserDetailRef.value.open();
  }
};
const handleDelete = (record: any, type: string) => {
  const ids = [];
  if (record && record.id) {
    ids.push(record.id);
  }
  const api = type === 'logoutByLoginId' ? logoutByLoginId : kickoutByLoginId;
  const msg = type === 'logoutByLoginId' ? '强制注销成功' : '踢下线成功';
  api({
    ids,
  }).then(() => {
    message.success(msg);
    requestData();
  });
};
onMounted(() => {
  requestData();
});
</script>
<template>
  <Page auto-content-height>
    <Grid>
      <template #ACTION="{ row }">
        <TableAction
          :actions="[
            {
              label: '踢下线',
              size: 'small',
              popConfirm: {
                title: '确定踢下线吗？',
                confirm: handleDelete.bind(null, row, 'kickoutByLoginId'),
              },
              disabled: row.isCurrentUser || row.superAdmin,
              tooltip:
                row.isCurrentUser || row.superAdmin
                  ? '当前用户或超级管理员不允许踢下线！'
                  : undefined,
              auth: ['admin', 'sys:user:kickoutByLoginId'], // 根据权限控制是否显示: 有权限，会显示
            },
            {
              label: '强制注销',
              size: 'small',
              popConfirm: {
                title: '确定强制注销吗？',
                confirm: handleDelete.bind(null, row, 'logoutByLoginId'),
              },
              disabled: row.isCurrentUser || row.superAdmin,
              tooltip:
                row.isCurrentUser || row.superAdmin
                  ? '当前用户或超级管理员不允许强制注销！'
                  : undefined,
              auth: ['admin', 'sys:user:logoutByLoginId'], // 根据权限控制是否显示: 有权限，会显示
            },
          ]"
        />
      </template>
    </Grid>
    <OnlineUserDetail ref="onlineUserDetailRef" @reload="requestData" />
  </Page>
</template>
